import { useEffect, useState } from 'react'
import { FC, useRouter } from '@tarojs/taro'
import { Subject, Subscription } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { AtForm, AtSwitch } from 'taro-ui';
import { useRoomUiFacade } from '@/hooks/useRoomUiFacade';

import "taro-ui/dist/style/components/input.scss";
import "taro-ui/dist/style/components/switch.scss";
import { View } from '@tarojs/components'
import "taro-ui/dist/style/components/button.scss" // 按需引入 
import './index.scss'

//密码设置
export const AllowShare: FC = () => {
  const [roomFacade, , , , , , , , , , , , , , , , , , , , , , , , , allowShare] = useRoomUiFacade();

  const router = useRouter();
  const roomId = router.params.roomId || "";

  // 初始化按钮接收参数subject，所有按钮或者操作都可以通过这个emmiter触发
  const initSubject = () => new Subject<any>();
  const [emitter, setEmitter] = useState<Subject<any>>(initSubject)

  const handleChange = (value: boolean) => {
    emitter.next({ allowShare: value, roomId: roomId });
  }

  useEffect(() => {
    const subscriptions: Subscription[] = [
      emitter.asObservable()
        .pipe(
          switchMap(roomFacade.editAllowShare)
        )
        .subscribe(
          {
            next: console.log,
            error: () => setEmitter(initSubject)
          }
        )
    ]

    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, [])

  return (
    <View className='index'>
      <View className='main'>
        <AtForm>
          <AtSwitch title='允许分享' checked={allowShare} onChange={handleChange} color={MAIN_COLOR} />
        </AtForm>
      </View>
    </View>
  )
}
export default AllowShare
